/**
 * Binary Tree Level Order Traversal
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example:
Given binary tree {3,9,20,#,#,15,7},
    3
   / \
  9  20
    /  \
   15   7
return its level order traversal as:
[
  [3],
  [9,20],
  [15,7]
]
 */
package com.xinpan.exercise;

import java.util.ArrayList;


public class LevelOrderTraversal {
    public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) 
    {
        // Start typing your Java solution below
        // DO NOT write main() function
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
        
        ArrayList<TreeNode> level = new ArrayList<TreeNode>();
        if(root != null)
        {
            level.add(root);
            ArrayList<Integer> levelVal = new ArrayList<Integer>();
            levelVal.add(root.val);
            result.add(levelVal);
        }

        while(level.size() > 0)
        {
            ArrayList<TreeNode> newLevel = new ArrayList<TreeNode>();
            ArrayList<Integer> levelVal = new ArrayList<Integer>();
            for(TreeNode node : level)
            {
                if(node.left != null)
                {
                    newLevel.add(node.left);
                    levelVal.add(node.left.val);
                }
                if(node.right != null)
                {
                    newLevel.add(node.right);
                    levelVal.add(node.right.val);
                }
            }
            if(levelVal.size() > 0)
                result.add(levelVal);
            
            level = newLevel;
        }
        
        return result;
    }
    
    
    class TreeNode {
    	 int val;
    	 TreeNode left;
    	 TreeNode right;
    	 TreeNode(int x) { val = x; }
    }
}
